package com.example.littleken.secret.Net;

import android.os.AsyncTask;

import com.example.littleken.secret.Config;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**本类封装你与服务器数据交流的具体方法
 * Created by littleken on 2018/4/24.
 */

public class NetConnection {
    /**
     *启动新消息，给服务器发送信息
     * @param url 服务器地址
     * @param method 通信类型
     * @param successCallback 通信状态
     * @param failCallback
     * @param kvs 通信消息,通过键值对实现
     */
    public NetConnection(final String url, final HttpMethod method, final SuccessCallback successCallback, final FailCallback failCallback, final String ... kvs){


        //通过多线程进行网络通信任务
        new AsyncTask<Void,Void,String>(){
            @Override
            protected String doInBackground(Void... params) {
                StringBuffer paronsStr = new StringBuffer();
                for (int i = 0; i <kvs.length ; i+=2) {
                    //把所有键与值拼装成 k=v & k=v & ……
                    paronsStr.append(kvs[i]).append("=").append(kvs[i+1]).append("&");
                }

                try {
                    URLConnection conn;
                    //根据连接方式构建不同的与服务器的连接方式
                    switch (method){
                        case POST:
                            conn = new URL(url).openConnection();
                            conn.setDoOutput(true);
                            //获取输出流，指定编码方式
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),Config.CHARSET));
                            //把消息写出到服务器
                            bw.write(paronsStr.toString());
                            bw.flush();
                            break;
                        case GET :
                            //把消息直接拼装到url之后发送给服务器
                            conn = new URL(url+"?"+paronsStr.toString()).openConnection();
                            break;
                        default:
                            return null;

                    }
                   // System.out.println("Request url"+conn.getURL());
                    // System.out.println("Request Data"+paronsStr);
                    //获取输入流，指定编码方式
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),Config.CHARSET));
                    String line = null;
                    //一行一行读服务器返回的消息
                    StringBuffer result = new StringBuffer();
                    while((line=br.readLine()) != null){
                        result.append(line);
                    }
                    //System.out.println("Request"+result);
                    //返回服务器返回消息
                    return result.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            /**
             * 主线程处理服务器返回消息
             * @param result
             */
            @Override
            protected void onPostExecute(String result) {
                if(result != null){
                    if (successCallback != null){
                        successCallback.onSuccess(result);
                    }
                }else{
                    if(failCallback != null){
                        failCallback.onFail();
                    }
                }
                super.onPostExecute(result);
            }
        }.execute();
    }
    //回调成功与失败接口
    public static interface SuccessCallback{
        void onSuccess(String result);
    }
    public static interface FailCallback{
        void onFail();
    }
}
